using Rogan.Data.SqlServer;
using System;
using System.Collections.Generic;
using System.Text;
namespace Rogan.Data.SqlServer9
{
	public class SqlServer9Provider : SqlServerProvider
	{
		public SqlServer9Provider(string connectionString) : base(connectionString)
		{
		}
		public override string GetSQLSelectTopClip(ExpressionTranslater translater)
		{
			StringBuilder stringBuilder = new StringBuilder();
			EntityQueryExpression expression = translater.Expression;
			if (expression.IsPagable)
			{
				IList<OrderByExpression> orderbys = expression.IsOrderBy ? expression.OrderByList : new List<OrderByExpression>
				{
					new OrderByExpression(expression.From.GetIdentityField(), OrderByDirection.Asc)
				};
				stringBuilder.Append("row_number() over (" + translater.TranslateOrderyByList(orderbys) + ") as rowId,");
				return stringBuilder.ToString();
			}
			return base.GetSQLSelectTopClip(translater);
		}
		public override void AdjustTranslater(ExpressionTranslater translater)
		{
			EntityQueryExpression expression = translater.Expression;
			if (expression.IsPagable)
			{
				AdjustPagable(translater);
			}
		}
		protected override void AdjustPagable(ExpressionTranslater translater)
		{
			string commandText = translater.CommandText;
			EntityQueryExpression expression = translater.Expression;
			string text = "SELECT * FROM ({OLDSQL}) AS tmptableinner WHERE rowId between {N} and {M}";
			text = text.Replace("{N}", (expression.StartIndex.Value + 1).ToString());
			text = text.Replace("{M}", (expression.EndIndex.Value + 1).ToString());
			text = text.Replace("{OLDSQL}", commandText);
			translater.SetCommandText(text);
		}
	}
}
